package com.whl.system.service.impl;

import com.whl.system.domain.Role;
import com.whl.system.mapper.RoleMapper;
import com.whl.system.service.IRoleService;
import com.whl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    // 添加重构
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addData(role);

    }

    // 抽取公共方法添加和修改时调用
    private void addData(Role role){
        List<Long> menus = role.getMenus();
        if(menus.size() > 0){
            roleMapper.addRoleMenus(role.getId(),menus);
        }
        List<Long> permissions = role.getPermissions();
        if(permissions.size() > 0){
            roleMapper.addRolePermissions(role.getId(),permissions);
        }
    }

    // 修改重构
    @Override
    @Transactional
    public void update(Role role) {
        // 先删除旧数据
        roleMapper.deleteRoleMenuByRoleId(role.getId());
        roleMapper.deleteRolePermissionByRoleId(role.getId());
        // 再添加新数据
        addData(role);
        super.update(role);
    }

    // 删除重构
    @Override
    @Transactional
    public void delete(Long id) {
        // 删除中间表数据
        roleMapper.deleteRoleMenuByRoleId(id);
        roleMapper.deleteRolePermissionByRoleId(id);
        roleMapper.deleteEmployeeRoleByRoleId(id);
        // 有外键关联，先删除关联数据 - 再删除主表数据
        super.delete(id);
    }

    // 批量删除重构
    @Override
    @Transactional
    public void patchDelete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
        super.patchDelete(ids);
    }
}
